package com.client.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.websocket.Session;
import javax.websocket.server.PathParam;

import org.apache.http.HttpRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.client.mapper.UserMapper;
import com.client.pojo.Post;
import com.client.pojo.User;
import com.client.service.PostService;
import com.client.service.UserService;

@Controller
public class UserController {
	@Autowired
	private UserService userService;




	//用户登录验证
	@RequestMapping(value="/login")
	public String toLogin(String username , String password,Model model,HttpServletRequest request ) {
		//1/验证 用户名 和 密码 是否为空 : 空的字符串

		User user = userService.checkLoginByUser(username, password);
		if (StringUtils.isEmpty(user) || user == null ) {
			//验证结果:数据填充
			//			model.addAttribute("errorInfo", "用户名或者密码不正确");
			//页面的跳转到 登录界面
			return "/loginfail";
		}
		//3/ 把数据放入到session对象中
		HttpSession  session=  request.getSession();
		session.setAttribute("sessionUser", user);
		session.setAttribute("username", username);
		session.setAttribute("userId", user.getId());

		return "forward:topostlist?userId="+user.getId();
	}
	/*
	 * 跳转注册页面
	 */
	@RequestMapping("/toregist")
	public String toregist(){
		return "/regist";
	}
	/*
	 * 跳转登陆页面
	 */
	@RequestMapping("/")
	public String tologin(){
		return "/login";
	}

	@RequestMapping("/userregist")
	public String regist(@PathParam("username")String username,@PathParam("password")String password ,@PathParam("nickname")String nickname){
		System.out.println(username+password+nickname);
		User user=new User();
		user.setUsername(username);
		user.setPassword(password);
		user.setNickname(nickname);
		userService.regist(user);
		return "/login";
	}
	/*
	 * ajax
	 */
	@RequestMapping("/ajax")
	@ResponseBody
	public void jiaoyan(HttpServletRequest req, HttpServletResponse resp, String username) throws Exception {
		List<User> userList = userService.findUsername(username);
		if (userList.size() != 0) {
			resp.getWriter().write("ON");
		}else{
			resp.getWriter().write("OK");
		}
	}

	/*
	 * 跳转登陆页面
	 */
	@RequestMapping("/returnlogin")
	public String returnlogin(){
		return "/login";
	}

}
